﻿namespace AiQiuQuan.Sport.Core.Tool
{
    /// <summary>
    /// 距离计算工具类
    /// </summary>
    public class DistanceTool
    {
        //地球半径，单位米
        private const double EARTH_RADIUS = 6378137;

        /// <summary>
        /// 计算两点位置的距离，返回两点的距离，单位 米
        /// 该公式为GOOGLE提供，误差小于0.2米
        /// </summary>
        /// <param name="lat1">第一点纬度</param>
        /// <param name="lng1">第一点经度</param>
        /// <param name="lat2">第二点纬度</param>
        /// <param name="lng2">第二点经度</param>
        /// <returns></returns>
        public static double GetDistance(decimal lat1, decimal lng1, decimal lat2, decimal lng2)
        {
            try
            {
                var radLat1 = Rad(lat1);
                var radLng1 = Rad(lng1);
                var radLat2 = Rad(lat2);
                var radLng2 = Rad(lng2);
                var a = radLat1 - radLat2;
                var b = radLng1 - radLng2;
                var result = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) + (Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2)))) * EARTH_RADIUS;
                return result;
            }
            catch
            {
                return 0;
            }
        }

        /// <summary>
        /// 计算两点位置的距离，返回两点的距离，单位 千米
        /// 该公式为GOOGLE提供，误差小于0.2米
        /// </summary>
        /// <param name="lat1">第一点纬度</param>
        /// <param name="lng1">第一点经度</param>
        /// <param name="lat2">第二点纬度</param>
        /// <param name="lng2">第二点经度</param>
        /// <returns></returns>
        public static double GetDistanceKM(decimal lat1, decimal lng1, decimal lat2, decimal lng2)
        {
            var result = (double)0;
            try
            {
                var radLat1 = Rad(lat1);
                var radLng1 = Rad(lng1);
                var radLat2 = Rad(lat2);
                var radLng2 = Rad(lng2);
                var a = radLat1 - radLat2;
                var b = radLng1 - radLng2;
                result = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) + (Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2)))) * EARTH_RADIUS;
            }
            catch
            {
            }

            return Math.Round(result / 1000, 1);
        }

        /// <summary>
        /// 经纬度转化成弧度
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        private static double Rad(decimal d)
        {
            return (double)d * Math.PI / 180d;
        }
    }
}
